<!DOCTYPE html>
<html lang="en" >
<head>
    <meta charset="UTF-8">
    <meta name="referrer" content="no-referrer" />

    <meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">
    <title>在线聊天</title>


    <!--图标库-->
    <link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css'>

    <!-- 默认样式-->
    <link rel="stylesheet" href="<?php echo base_url(); ?>public/chat/css/reset.min.css">

    <!-- 主要样式-->
    <link rel="stylesheet" href="<?php echo base_url(); ?>public/chat/css/style.css">

    <script src="https://libs.baidu.com/jquery/1.9.1/jquery.min.js"></script>
    <script src="<?php echo base_url(); ?>public/layui/layui.js" charset="utf-8"></script>

    <script type="text/javascript" src="<?php echo base_url(); ?>public/jquery.min.js"></script>
    <script type="text/javascript" src='<?php echo base_url(); ?>public/chat/js/handlebars.min.js'></script>
    <script type="text/javascript" src='<?php echo base_url(); ?>public/chat/js/list.min.js'></script>
    <script type="text/javascript" src="<?php echo base_url(); ?>public/chat/js/script.js"></script>

    <script type="text/javascript" src="<?php echo base_url(); ?>public/chat/rsa/jsbn.js"></script>
    <script type="text/javascript" src="<?php echo base_url(); ?>public/chat/rsa/prng4.js"></script>
    <script type="text/javascript" src="<?php echo base_url(); ?>public/chat/rsa/rng.js"></script>
    <script type="text/javascript" src="<?php echo base_url(); ?>public/chat/rsa/rsa.js"></script>

    <!-- 表情相关-->
    <link rel="stylesheet" href="<?php echo base_url(); ?>public/emoji/dist/css/jquery.emoji.css"/>
    <link rel="stylesheet" href="<?php echo base_url(); ?>public/emoji/lib/css/railscasts.css"/>
    <link rel="stylesheet" href="<?php echo base_url(); ?>public/emoji/dist/css/index.css"/>

    <script src="<?php echo base_url(); ?>public/emoji/lib/script/highlight.pack.js"></script>
    <script src="<?php echo base_url(); ?>public/emoji/dist/js/jquery.emoji.min.js"></script>
    <script src="<?php echo base_url(); ?>public/emoji/dist/js/emoji.list.js"></script>
    <script src="<?php echo base_url(); ?>public/emoji/src/js/jquery.emoji.js"></script>
    <!-- 表情相关-->

</head>

<style>
    .layui-layer layui-layer-dialog{
        width: 280px;
    }
    
    .note_sp{
        color: darkkhaki;
    }

    /*为空时显示 element attribute content*/
    #editor:empty:before{
        content: attr(placeholder);   /* element attribute*/
    }
    /*焦点时内容为空*/
    #editor:focus:before {
        content: none;
    }
</style>
<body>

<div class="container clearfix">
    <div class="people-list" id="people-list">
        <div class="search">
            <input type="button" onclick="avatarUpload()" value="头像投稿" />

        </div>
        <ul class="list" id="leftList" style="overflow: overlay;">

            <a href="javascript:;" style="color: white" onclick="goChat('NNh')">
                <li class="clearfix">
                    <img src="<?php echo base_url().'/public/home.png'; ?>" style="width: 55px;height: 55px;" alt="avatar" />
                    <div class="about">
                        <div class="name">大厅</div>
                        <div class="status">
                            <i class="fa fa-circle online" style="float: left;margin-top: 6px;"></i><span id="newMsg_NNh"></span>
                        </div>
                    </div>
                </li>
            </a>

            <?php if(!empty($list)){ foreach ($list as $val){ ?>
                <a href="javascript:;" id="left_<?php echo $val['id'];?>" style="color: white" onclick="goChat('<?php echo $val['id'];?>','<?php echo $val['nick_name'];?>','<?php echo $val['url'];?>')">
                    <li class="clearfix">
                        <img src="<?php echo $val['url']; ?>" style="width: 55px;height: 55px;" alt="avatar" />
                        <div class="about">
                            <div class="name" id="nick_tag_<?php echo $val['id']?>"><?php echo $val['nick_name'];?></div>
                            <div class="status">
                                <i class="fa fa-circle online" style="float: left;margin-top: 6px;"></i><span class="note_sp" id="newMsg_<?php echo $val['id']?>"></span>
                            </div>
                        </div>
                    </li>
                </a>
            <?php }} ?>

        </ul>
    </div>

    <div class="chat">
        <div class="chat-header clearfix">
            <img id="to_avatar" src="<?php echo base_url().'/public/home.png'; ?>" style="width: 55px;height: 55px;" alt="avatar" />

            <div class="chat-about">
                <div class="chat-with" id="to_name">大厅</div>
                <div class="chat-num-messages" id="hone_desc">展示所有聊天记录(注意肾体)</div>
            </div>

            <div onclick="editNick()" style="position: absolute;margin-left: 342px;margin-top: 25px;color: #9293B7">
                昵称
                <i class="fa fa-pencil" aria-hidden="true"></i>
            </div>

            <img style="float: right;width: 55px;height: 55px;" id="homeMyHead" src="<?php echo base_url().'/public/def.jpg'; ?>" alt="">
        </div> <!-- end chat-header -->

        <div class="chat-history" id="chat-history">
            <ul id="chat_box">

            </ul>

        </div> <!-- end chat-history -->

        <a href="javascript:;" style="text-decoration:none; display: none" id="showNew" onclick="goNew()">
            <div style="width: 100%;text-align: center;color:#434651;background-color: lightcoral;font-weight: bold;">
                有新消息,点击查看
            </div>
        </a>

        <div class="chat-message clearfix">

            <div id="editor" placeholder='请输入内容' contenteditable="true"></div>

            <i onclick="upImg()" style="font-size: 20px;" class="fa fa-file-image-o"></i>&nbsp;&nbsp;
            <i onclick="upVideo()" style="font-size: 20px;" class="fa fa-play-circle-o"></i>
            <span id="addEmojiBtn"><i id="emoji_btn" style="font-size: 22px;margin-left: 6px;" class="fa fa-smile-o"></i></span>

            <button id="sendMsg" onclick="sendMsg()">发送</button>

        </div> <!-- end chat-message -->

    </div> <!-- end chat -->

</div> <!-- end container -->

<div style="color: rosybrown;position: fixed;bottom: 0;">
    @作者：叶念安 QQ:1298025852
    <a href="http://nmsl.taoerhuo.top/" target="_blank" style="text-decoration:none;color: cadetblue;margin-left: 10px;">骂人宝典</a>
    <a href="javascript:;" onclick="backGarden()" style="text-decoration:none;color: cadetblue;margin-left: 10px;">秘密后花园</a>
    <a href="javascript:;" onclick="showGroup()" style="text-decoration:none;color: cadetblue;margin-left: 10px;">入群 <span id="spG" style="display:none">731534839</span> </a>
</div>

<input type="hidden" id="user_id">
<input type="hidden" id="client_id">
<input type="hidden" id="to_uid" value="">
<input type="hidden" id="page" value="0">


<div id="outerdiv" style="position:fixed;top:0;left:0;background:rgba(0,0,0,0.7);z-index:2;width:100%;height:100%;display:none;">
    <div id="innerdiv" style="position:absolute;">
        <img id="bigimg2" style="border:5px solid #fff;" src="" />
    </div>
</div>

</body>
<script>
    layui.use('layer',function () {

        /**
         * 与GatewayWorker建立websocket连接，域名和端口改为你实际的域名端口，
         * 其中端口为Gateway端口，即start_gateway.php指定的端口。
         * start_gateway.php 中需要指定websocket协议，像这样
         * $gateway = new Gateway(websocket://0.0.0.0:8282);
         */

        ws = new WebSocket("wss://www.taoerhuo.top:8282");

        // 服务端主动推送消息时会触发这里的onmessage
        ws.onmessage = function(e){
            // json数据转换成js对象
            var data = eval("("+e.data+")");
            var type = data.type || '';

            //console.log(data);

            switch(type){
                // Events.php中返回的init类型的消息，将client_id发给后台进行uid绑定
                case 'init':
                    layer.msg(data.msg);

                    // 利用jquery发起ajax请求，将client_id发给后端进行用户生成并与用户id绑定
                    var request_url = "<?php echo base_url().'index.php/'; ?>"+'index/bindUser';

                    var base = "<?php echo base_url().'index.php/index/captcha';?>";

                    if (data.isAlert)
                    {
                        //设置昵称
                        layer.open({
                            title:"你的昵称",
                            content: ' <input style="width: 215px;height: 33px;" placeholder="您的昵称" type="text" id="nick_val" class="layui-input"><br/>' +
                                '<input style="width: 114px;height: 33px;margin-top: 5px;" placeholder="验证码" type="text" id="code" class="layui-input">' +
                                '<div style="margin-left: 115px;margin-top: -33px;"><img src="'+base+'" id="code_img" onclick="getCode()" title="看不清换一涨" style="width: 100px;height: 33px" align="absmiddle"></div>',
                            btn: ['确认'],
                            btn1: function(index){
                                //按钮【按钮一】的回调
                                var val = $("#nick_val").val();

                                var code = $("#code").val();

                                if (!val || !code)
                                {
                                    alert('请输入昵称和验证码');
                                } else {
                                    $.ajax({
                                        type: "POST",
                                        dataType: "json",
                                        url: request_url,
                                        async: false,
                                        beforeSend: function(request) {
                                            request.setRequestHeader("Chat", cmdEncrypt());
                                        },
                                        data: {
                                            client_id: data.client_id,
                                            nick:val,
                                            real_ip:data.real_ip,
                                            code:code
                                        },
                                        success: function (result) {
                                            if (result.code != 200)
                                            {
                                                alert(result.msg)
                                                
                                                //layer.msg(result.msg);
                                                return;
                                            }

                                            //设置头像和昵称
                                            $("#myAvatar").attr('src',result.data.avatar);

                                            //设置当前用户id
                                            $("#user_id").val(result.data.user_id);
                                            $("#client_id").val(data.client_id);
                                            $("#to_uid").val(data.public);

                                            //我的头像
                                            $("#homeMyHead").attr('src',result.data.avatar);

                                            //聊天记录
                                            getChatLog(result.data.list,result.data.user_id);
                                        },
                                        error : function() {
                                            layer.msg('服务器连接失败');
                                        }
                                    });

                                    layer.close(index);//关闭弹框
                                }
                            },

                        });
                    } else {
                        $.ajax({
                            type: "POST",
                            dataType: "json",
                            async: false,
                            url: request_url,
                            data: {
                                client_id: data.client_id,
                                real_ip:data.real_ip
                            },
                            beforeSend: function(request) {
                                request.setRequestHeader("Chat", cmdEncrypt());
                            },
                            success: function (result) {
                                if (result.code != 200)
                                {
                                    layer.msg(result.msg);
                                    return;
                                }

                                //设置头像和昵称
                                $("#myAvatar").attr('src',result.data.avatar);

                                //设置当前用户id
                                $("#user_id").val(result.data.user_id);
                                $("#client_id").val(data.client_id);
                                $("#to_uid").val(data.public);

                                //我的头像
                                $("#homeMyHead").attr('src',result.data.avatar);

                                //聊天记录
                                getChatLog(result.data.list,result.data.user_id);
                            },
                            error : function() {
                                layer.msg('服务器连接失败');
                            }
                        });
                    }

                    break;
                case 'text':
                    //新消息-先判断是大厅消息还是私人消息
                    var to_uid  = $("#to_uid").val(); //当前对话是大厅还是私人
                    var user_id  = $("#user_id").val();

                    //当前对话等于发来的人id || 当前对话（大厅）
                    if ((to_uid == data.from_uid && (user_id == data.to_uid)) || (to_uid == data.to_uid))
                    {
                        //正在聊天
                        var log = '<li>' +
                            '<div class="message-data"><span class="message-data-name"><img style="width: 40px;height:40px;margin-bottom: -13px;" src="'+data.avatar+'" alt="avatar" />'+data.nick+'</span><span style="font-size: 12px;color: brown">('+data.city+')</span> <span class="message-data-time" >'+data.time+'</span></div>' +
                            '<div style="line-height: 18px;" class="message my-message">'+data.msg+'</div>'+
                            '</li>';

                        $("#chat_box").append(log);

                        if (to_uid != 'NNh')
                        {
                            //滚动条定位至最下方
                            $("#chat-history").scrollTop($("#chat-history")[0].scrollHeight);
                        } else {
                            //判断滚动条是否在最底部
                            var che = parseInt($("#chat-history")[0].scrollHeight) - parseInt($("#chat-history").scrollTop());

                            if (che >= 1500)
                            {
                                $("#showNew").show();
                            } else {
                                $("#chat-history").scrollTop($("#chat-history")[0].scrollHeight);
                            }
                        }

                    } else {
                        var msg = data.msg;

                        var m   = '';

                        if (msg.indexOf('<img') == -1 && msg.indexOf('<video') == -1) {
                            m = msg.substr(0,10);
                        } else if(msg.indexOf('<img') != -1) {
                            m = '[图片]';
                        } else if(msg.indexOf('<video') != -1) {
                            m = '[视频]';
                        }

                        if (data.to_uid == 'NNh')
                        {
                            //大厅消息
                            $("#newMsg_NNh").text(m);
                        } else {
                            //私人消息
                            $("#newMsg_"+data.from_uid).text(m);
                        }

                    }
                    break;
                case 'connect':
                    //有新用户连接--只添加一次
                    if(!document.getElementById('left_'+data.id)){
                        var newCon = '<a href="javascript:;" id="left_'+data.id+'" style="color: white;" onclick="goChat('+"'"+data.id+"'"+', '+"'"+data.nick+"'"+','+"'"+data.avatar+"'"+')">' +
                            '<li class="clearfix"><img src="'+data.avatar+'" style="width: 55px;height: 55px;" alt="avatar"><div class="about">'+
                            '<div class="name" id="nick_tag_'+data.id+'">'+data.nick+'</div><div class="status"><i class="fa fa-circle online" style="float: left;margin-top: 6px;"></i><span class="note_sp" id="newMsg_'+data.id+'"></span>'+
                            '</div></div></li>'+
                            '</a>';

                        $("#leftList").append(newCon);
                    }
                    break;
                case 'change':
                    //有用户改昵称
                    $("#nick_tag_"+data.id).text(data.nick);
                    break;
                case 'close':
                    //有用户断开连接
                    //id为空重新获取
                    if (data.id == '')
                    {
                        var request_url = "<?php echo base_url().'index.php/'; ?>"+'index/getUserByClient';
                        $.ajax({
                            type: "POST",
                            dataType: "json",
                            url: request_url,
                            data: {
                                real_ip:data.real_ip,
                            },
                            success: function (result) {

                                if (result.code != 200)
                                {
                                    // console.log(result);
                                    // console.log(data.real_ip+'断开连接移除失败');
                                } else {
                                    $("#left_"+result.data.id).remove();
                                }
                            },
                            error : function() {
                                console.log(data.real_ip+'断开连接服务器连接失败');
                            }
                        });
                    } else {
                        $("#left_"+data.id).remove();
                    }
                    break;
                default :
                //alert(e.data);
            }
        };
        
    //     ws.onopen = function(){
    // 		setInterval(function(){ 
    // 		    console.info("心跳检测");
    // 		    ws.send('ping');
    // 		},30000);
    // 	}
	
	    
    });
    
    function getCode()
    {
        var base = "<?php echo base_url().'index.php/'.'index/captcha';?>";
        $("#code_img").attr("src",base+'?' + Math.random());
    }
    
    function showGroup()
    {
        $("#spG").show();
        
        layer.alert('<span style="color:black">lsp高峰论坛：731534839</span>', {
          skin: 'layui-layer-molv' //样式类名
          ,closeBtn: 0
        });
    
    }

    //发送聊天内容
    function sendMsg()
    {
        $("#sendBut").attr('disabled',true);

        var content = $("#editor").html();

        if (!content)
        {
            $("#sendBut").attr('disabled',false);
            layer.msg('不能发送空白消息');
            return;
        }

        var user_id     = $("#user_id").val();
        var to_uid      = $("#to_uid").val();
        var client_id   = $("#client_id").val();
        var request_url = "<?php echo base_url().'index.php/'; ?>"+'index/chatRecord';

        if (!user_id)
        {
            $("#sendBut").attr('disabled',false);
            layer.msg('请刷新后重试');
            return;
        }

        $.ajax({
            type: "POST",
            dataType: "json",
            async: false,
            url: request_url,
            data: {
                content: content,
                user_id: user_id,
                to_uid : to_uid,
                client_id:client_id,
            },
            beforeSend: function(request) {
                request.setRequestHeader("Chat", cmdEncrypt());
            },
            success: function (result) {
                $("#sendBut").attr('disabled',false);

                if (result.code != 200)
                {
                    layer.msg(result.msg);
                    return false;
                }

                //内容渲染
                var newMsg = '<li class="clearfix">' +
                    '<div class="message-data align-right"><span class="message-data-time" >'+result.data.time+'</span> &nbsp; &nbsp;<span class="message-data-name" >'+result.data.nick+'</span> <img style="width: 40px;height:40px;margin-bottom: -13px;" src="'+result.data.avatar+'" alt="avatar" /></div>' +
                    '<div style="line-height: 18px;" class="message other-message float-right">'+result.data.content+'</div>'+
                    '</li>';

                $("#chat_box").append(newMsg);

                $("#editor").html('');

                var div = document.getElementById('chat-history');
                div.scrollTop = div.scrollHeight;
            },
            error : function() {
                $("#sendBut").attr('disabled',false);
                layer.msg('服务器连接失败');
            }
        });
    }

    //渲染聊天记录
    function getChatLog(list,now_uid)
    {
        let arrNew = new Array();

        for (var i = list.length - 1; i >= 0; i--) {

            var log = '';
            if (list[i].uid == now_uid)
            {
                log = '<li class="clearfix">' +
                    '<div class="message-data align-right"><span class="message-data-time" >'+list[i].create_time+'</span> &nbsp; &nbsp;<span class="message-data-name" >'+list[i].nick_name+'</span> <img style="width: 40px;height:40px;margin-bottom: -13px;" src="'+list[i].url+'" alt="avatar" /></div>' +
                    '<div style="line-height: 18px;" class="message other-message float-right">'+list[i].content+'</div>'+
                    '</li>';
            } else {
                log = '<li>' +
                    '<div class="message-data"><span class="message-data-name"><img style="width: 40px;height:40px;margin-bottom: -13px;" src="'+list[i].url+'" alt="avatar" />'+list[i].nick_name+'</span> <span style="font-size: 12px;color: brown">('+list[i].city+')</span><span class="message-data-time" >'+list[i].create_time+'</span></div>' +
                    '<div style="line-height: 18px;" class="message my-message">'+list[i].content+'</div>'+
                    '</li>';
            }

            arrNew.push(log);
        }

        $("#chat_box").html(arrNew);

        //滚动条定位至最下方
        $("#chat-history").scrollTop($("#chat-history")[0].scrollHeight);
    }

    //点击在线用户获取聊天记录
    function goChat(to_uid,nick='',avatar='')
    {
        $("#to_uid").val(to_uid); //赋值当前聊天对象

        var user_id     = $("#user_id").val();
        var request_url = "<?php echo base_url().'index.php/'; ?>"+'index/getPageChatRecord';

        if (nick && avatar)
        {
            $("#hone_desc").hide();
            $("#to_name").text(nick);
            $("#to_avatar").attr('src',avatar);
            $("#to_name").css("margin-top","12px");
        } else {
            //回到大厅
            $("#hone_desc").show();
            $("#to_name").text('大厅');
            $("#to_name").css("margin-top","0px");
            $("#to_avatar").attr('src',"<?php echo base_url().'/public/home.png'; ?>");
        }

        //清空消息提示
        $("#newMsg_"+to_uid).text('');

        if (page != '')
        {
            $.ajax({
                type: "POST",
                dataType: "json",
                url: request_url,
                data: {
                    user_id: user_id,
                    to_uid: to_uid,
                    page:0,
                },
                success: function (result) {

                    layer.msg(result.msg);

                    if (result.code != 200)
                    {
                        return false;
                    }

                    $("#page").val(1);

                    //渲染聊天记录
                    getChatLog(result.data.list,user_id);
                },
                error : function() {
                    $("#sendBut").attr('disabled',false);
                    layer.msg('服务器连接失败');
                }
            });
        }
    }

    //改昵称
    function editNick()
    {
        layer.prompt({title: '请输入新昵称', formType: 3}, function (val, index) {

            val = clearSpace(val);

            if (!val)
            {
                layer.msg('请输入昵称');
                return;
            }

            var request_url  = "<?php echo base_url().'index.php/'; ?>"+'index/editNick';

            var user_id      = $("#user_id").val();
            var client_id    = $("#client_id").val();

            $.ajax({
                type: "POST",
                dataType: "json",//预期服务器返回的数据类型
                data:{
                    nick:val,
                    user_id:user_id,
                    client_id:client_id,
                },
                url: request_url,
                async: false,
                beforeSend: function(request) {
                    request.setRequestHeader("Chat", cmdEncrypt());
                },
                success: function (result) {
                    layer.msg(result.msg);
                    if (result.code==200)
                    {
                        layer.close(index);
                    }
                },
                error: function () {
                    layer.msg('服务器连接失败');
                }
            });
        });
    }

    //检测滚动条是否到达顶部
    $(document).ready(function (){

        var nScrollTop  = 0;   //滚动到的当前位置

        var request_url = "<?php echo base_url().'index.php/'; ?>"+'index/getPageChatRecord';

        $("#chat-history").scroll(function(){
            var page    = $("#page").val();

            if (parseInt(page) == parseInt("0"))
            {
                page = 1;
            }

            nScrollTop = $(this)[0].scrollTop;

            if(nScrollTop == 0)
            {
                var now_uid = $("#user_id").val();

                var to_uid  = $("#to_uid").val();

                var user_id     = $("#user_id").val();

                //获取上一页
                $.ajax({
                    type: "POST",
                    dataType: "json",
                    url: request_url,
                    data: {
                        page: page,
                        to_uid:to_uid,
                        user_id:user_id,
                    },
                    success: function (result) {
                        layer.msg(result.msg);
                        if (result.code != 200)
                        {
                            return;
                        }

                        $("#page").val(parseInt(page) + parseInt("1"));

                        var New = '';

                        var list = result.data.list;

                        for (var i = list.length - 1; i >= 0; i--) {

                            var log = '';
                            if (list[i].uid == now_uid)
                            {
                                log = '<li class="clearfix">' +
                                    '<div class="message-data align-right"><span class="message-data-time" >'+list[i].create_time+'</span> &nbsp; &nbsp;<span class="message-data-name" >'+list[i].nick_name+'</span> <img style="width: 40px;height:40px;margin-bottom: -13px;" src="'+list[i].url+'" alt="avatar" /></div>' +
                                    '<div style="line-height: 18px;" class="message other-message float-right">'+list[i].content+'</div>'+
                                    '</li>';
                            } else {
                                log = '<li>' +
                                    '<div class="message-data"><span class="message-data-name"><img style="width: 40px;height:40px;margin-bottom: -13px;" src="'+list[i].url+'" alt="avatar" />'+list[i].nick_name+'</span><span style="font-size: 12px;color: brown">('+list[i].city+')</span> <span class="message-data-time" >'+list[i].create_time+'</span></div>' +
                                    '<div style="line-height: 18px;" class="message my-message">'+list[i].content+'</div>'+
                                    '</li>';
                            }

                            New = New + log;
                        }

                        var old = $("#chat_box").html();

                        var newLog = New + old;

                        $("#chat_box").html(newLog);

                        if (list.length > 0)
                        {
                            //设置滚动条往下一点
                            $("#chat-history").scrollTop(250);
                        }
                    },
                    error : function() {
                        layer.msg('服务器连接失败');
                    }
                });
            }

        });
    });

    //检测滚动条是否到达底部
    $(document).ready(function (){
        var nScrollHight = 0; //滚动距离总长(注意不是滚动条的长度)
        var nScrollTop = 0;   //滚动到的当前位置
        var nDivHight = $("#chat-history").height();
        $("#chat-history").scroll(function(){
            nScrollHight = $(this)[0].scrollHeight;
            nScrollTop = $(this)[0].scrollTop;
            var paddingBottom = parseInt( $(this).css('padding-bottom') ),paddingTop = parseInt( $(this).css('padding-top') );
            if(nScrollTop + paddingBottom + paddingTop + nDivHight >= nScrollHight)
            {
                $("#showNew").hide();
            }
        });
    });

    //定位只最下方
    function goNew()
    {
        $("#showNew").hide();
        $("#chat-history").scrollTop($("#chat-history")[0].scrollHeight);
    }

    //表情
    function test()
    {
        layer.msg('开发中');
    }

    //回车提交
    $(document).keyup(function(event){
        if(event.keyCode ==13){
            $("#sendMsg").trigger("click");
        }
    });

    //头像投稿
    function avatarUpload()
    {
        layer.open({
            title:"欢迎投稿头像，接受任何风格",
            content: ' <input style="width: 215px;height: 33px;" onchange="uploadDesc(this.value)" type="file" accept="image/gif,image/jpeg,image/jpg,image/png" multiple="multiple" id="img_up" class="layui-input">' +
                '<div id="FileArea" style="color: black"></div>',
            btn: ['上传','取消'],
            btn1: function(index){
                //按钮【按钮一】的回调

                var load = layer.load(1, {
                    shade: [0.1,'#fff'] //0.1透明度的白色背景
                });

                var request_url = "<?php echo base_url().'index.php/'; ?>"+'index/uploadAvatar';

                var uid = $('#user_id').val();

                var formData = new FormData();
                formData.append('image', $('#img_up')[0].files[0]);
                formData.append('uid', uid);

                $.ajax({
                    type: "POST",
                    dataType: "json",
                    cache: false,
                    processData: false,
                    contentType: false,
                    url: request_url,
                    data: formData,
                    beforeSend: function(request) {
                        request.setRequestHeader("Chat", cmdEncrypt());
                    },
                    success: function (result) {
                        layer.close(load);
                        layer.msg(result.msg);
                        if (result.code != 200)
                        {
                            return false;
                        }

                        layer.close(index);//关闭弹框
                    },
                    error : function() {
                        layer.close(load);
                        layer.msg('服务器连接失败');
                    }
                });
            },
        });
    }

    function uploadDesc(val)
    {
        $("#FileArea").text(val);
    }

    //秘密后花园
    function backGarden()
    {
        layer.prompt({title: '请输入令牌', formType: 1}, function (pass, index) {

            pass = clearSpace(pass);

            if (!pass)
            {
                layer.msg('请输入令牌');
                return;
            }

            var verifyResult= verifyPsw(pass);

            if (verifyResult) {
                layer.close(index);

                //跳转
                window.open("<?php echo base_url().'index.php/'; ?>"+'verify/verifyHtml?pass='+pass);
            } else {
                layer.msg('令牌错误');
                return;
            }
        });
    }

    // 验证口令
    function  verifyPsw(pass)
    {
        var flag = '';
        var request_url  = "<?php echo base_url().'index.php/'; ?>"+'verify/verifyPsw';

        $.ajax({
            type: "POST",
            dataType: "json",//预期服务器返回的数据类型
            data:{
                pass:pass,
            },
            url: request_url,
            async: false,
            success: function (result) {
                if (result.code==200)
                {
                    flag = true
                } else {
                    flag = false;
                }
            },
            error: function () {
                layer.msg('服务器连接失败');
            }
        });

        return flag;
    }


    // 清空字符串空格
    function clearSpace(str)
    {
        return str.replace(/\s+/g,"");
    }

</script>
<script>
    //表情
    hljs.initHighlightingOnLoad();

    $("#addEmojiBtn").click(function () {

        $("#addEmojiBtn").unbind("click"); //移除click事件

        $("#editor").emoji({
            button: "#emoji_btn",
            showTab: false,
            animation: 'slide',
            basePath: 'public/emoji/images/emoji',
            icons: emojiLists   // 注：详见 js/emoji.list.js
        });
    });

    //发送图片
    function upImg()
    {
        layer.open({
            title:"请选择图片",
            content: ' <input style="width: 215px;height: 33px;" onchange="uploadDesc(this.value)" type="file" accept="image/gif,image/jpeg,image/jpg,image/png" multiple="multiple" id="sendImg" class="layui-input">' +
                '<div id="FileArea" style="color: black"></div>',
            btn: ['发送','取消'],
            btn1: function(index){

                var load = layer.load(1, {
                    shade: [0.1,'#fff'] //0.1透明度的白色背景
                });

                //按钮【按钮一】的回调
                var request_url = "<?php echo base_url().'index.php/'; ?>"+'index/sendImage';

                var uid    = $('#user_id').val();
                var to_uid = $('#to_uid').val();
                var client_id   = $("#client_id").val();

                var formData = new FormData();
                formData.append('image', $('#sendImg')[0].files[0]);
                formData.append('uid', uid);
                formData.append('to_uid', to_uid);
                formData.append('client_id', client_id);

                $.ajax({
                    type: "POST",
                    dataType: "json",
                    cache: false,
                    processData: false,
                    contentType: false,
                    url: request_url,
                    data: formData,
                    beforeSend: function(request) {
                        request.setRequestHeader("Chat", cmdEncrypt());
                    },
                    success: function (result) {

                        layer.close(load);
                        if (result.code != 200)
                        {
                            layer.msg(result.msg);

                            return false;
                        } else {
                            layer.close(index);//关闭弹框

                            //渲染消息
                            var newMsg = '<li class="clearfix">' +
                                '<div class="message-data align-right"><span class="message-data-time" >'+result.data.time+'</span> &nbsp; &nbsp;<span class="message-data-name" >'+result.data.nick+'</span> <img style="width: 40px;height:40px;margin-bottom: -13px;" src="'+result.data.avatar+'" alt="avatar" /></div>' +
                                '<div style="line-height: 18px;" class="message other-message float-right">'+result.data.content+'</div>'+
                                '</li>';

                            $("#chat_box").append(newMsg);

                            $("#editor").html('');

                            var div = document.getElementById('chat-history');
                            div.scrollTop = div.scrollHeight;
                        }

                    },
                    error : function() {
                        layer.close(load);
                        layer.msg('服务器连接失败');
                    }
                });
            },
        });
    }
    
    //发送视频
    function upVideo()
    {
        //layer.msg('开发中');return;
        layer.open({
            title:"请选择视频",
            content: ' <input style="width: 215px;height: 33px;" onchange="uploadDesc(this.value)" type="file" accept="video/mp4" multiple="multiple" id="sendVideo" class="layui-input">' +
                '<div id="FileArea" style="color: black"></div>',
            btn: ['发送','取消'],
            btn1: function(index){

                var load = layer.load(1, {
                    shade: [0.1,'#fff'] //0.1透明度的白色背景
                });

                //按钮【按钮一】的回调
                var request_url = "<?php echo base_url().'index.php/'; ?>"+'index/sendImage';

                var uid    = $('#user_id').val();
                var to_uid = $('#to_uid').val();
                var client_id   = $("#client_id").val();

                var formData = new FormData();
                formData.append('image', $('#sendVideo')[0].files[0]);
                formData.append('uid', uid);
                formData.append('to_uid', to_uid);
                formData.append('client_id', client_id);

                $.ajax({
                    type: "POST",
                    dataType: "json",
                    cache: false,
                    processData: false,
                    contentType: false,
                    url: request_url,
                    data: formData,
                    beforeSend: function(request) {
                        request.setRequestHeader("Chat", cmdEncrypt());
                    },
                    success: function (result) {

                        layer.close(load);
                        if (result.code != 200)
                        {
                            layer.msg(result.msg);

                            return false;
                        } else {
                            layer.close(index);//关闭弹框

                            //渲染消息
                            var newMsg = '<li class="clearfix">' +
                                '<div class="message-data align-right"><span class="message-data-time" >'+result.data.time+'</span> &nbsp; &nbsp;<span class="message-data-name" >'+result.data.nick+'</span> <img style="width: 40px;height:40px;margin-bottom: -13px;" src="'+result.data.avatar+'" alt="avatar" /></div>' +
                                '<div style="line-height: 18px;" class="message other-message float-right">'+result.data.content+'</div>'+
                                '</li>';

                            $("#chat_box").append(newMsg);

                            $("#editor").html('');

                            var div = document.getElementById('chat-history');
                            div.scrollTop = div.scrollHeight;
                        }

                    },
                    error : function() {
                        layer.close(load);
                        layer.msg('服务器连接失败');
                    }
                });
            },
        });
    }
</script>

<script>
    $(document).ready(function (){
        $(document).on('click','.pic_u',function(){
            var _this = $(this);//将当前的pimg元素作为_this传入函数
            imgShow("#outerdiv", "#innerdiv", "#bigimg2", _this);
        });
    });

    function imgShow(outerdiv, innerdiv, bigimg, _this){
        var src = _this.attr("src");//获取当前点击的pimg元素中的src属性
        $(bigimg).attr("src", src);//设置#bigimg元素的src属性
        /*获取当前点击图片的真实大小，并显示弹出层及大图*/
        $("<img/>").attr("src", src).load(function(){
            var windowW = $(window).width();//获取当前窗口宽度
            var windowH = $(window).height();//获取当前窗口高度
            var realWidth = this.width;//获取图片真实宽度
            var realHeight = this.height;//获取图片真实高度
            var imgWidth, imgHeight;
            var scale = 1;//缩放尺寸，当图片真实宽度和高度大于窗口宽度和高度时进行缩放
            if(realHeight>windowH*scale) {//判断图片高度
                imgHeight = windowH*scale;//如大于窗口高度，图片高度进行缩放
                imgWidth = imgHeight/realHeight*realWidth;//等比例缩放宽度
                if(imgWidth>windowW*scale) {//如宽度扔大于窗口宽度
                    imgWidth = windowW*scale;//再对宽度进行缩放
                }
            } else if(realWidth>windowW*scale) {//如图片高度合适，判断图片宽度
                imgWidth = windowW*scale;//如大于窗口宽度，图片宽度进行缩放
                imgHeight = imgWidth/realWidth*realHeight;//等比例缩放高度
            } else {//如果图片真实高度和宽度都符合要求，高宽不变
                imgWidth = realWidth;
                imgHeight = realHeight;
            }
            $(bigimg).css("width",imgWidth);//以最终的宽度对图片缩放
            var w = (windowW-imgWidth)/2;//计算图片与窗口左边距
            var h = (windowH-imgHeight)/2;//计算图片与窗口上边距
            $(innerdiv).css({"top":h, "left":w});//设置#innerdiv的top和left属性
            $(outerdiv).fadeIn("fast");//淡入显示#outerdiv及.pimg
        });
        $(outerdiv).click(function(){//再次点击淡出消失弹出层
            $(this).fadeOut("fast");
        });
    }

</script>

<script type="text/javascript">
    //判断手机打开还是电脑打开
    function browserRedirect() {
        var sUserAgent = navigator.userAgent.toLowerCase();
        var bIsIpad = sUserAgent.match(/ipad/i) == "ipad";
        var bIsIphoneOs = sUserAgent.match(/iphone os/i) == "iphone os";
        var bIsMidp = sUserAgent.match(/midp/i) == "midp";
        var bIsUc7 = sUserAgent.match(/rv:1.2.3.4/i) == "rv:1.2.3.4";
        var bIsUc = sUserAgent.match(/ucweb/i) == "ucweb";
        var bIsAndroid = sUserAgent.match(/android/i) == "android";
        var bIsCE = sUserAgent.match(/windows ce/i) == "windows ce";
        var bIsWM = sUserAgent.match(/windows mobile/i) == "windows mobile";
        if (bIsIpad || bIsIphoneOs || bIsMidp || bIsUc7 || bIsUc || bIsAndroid || bIsCE || bIsWM) {
            //移动端
            alert('手机端暂未完善，请在电脑端打开');

        } else {
            //pc端

        }
    }
    browserRedirect();
</script>

</html>